$(function () {
    var loading = weui.loading('loading', {
        className: 'custom-classname'
    });
    var gid = Common.fn.getUrlParam('gid'),
        bid = Common.fn.getUrlParam('bid') || 0,
        result = Model.goods.buyerGoodsDetail({
            goodId: gid,
            businessId: bid
        });
    if (!sessionStorage.getItem('hmdj_stopError')) {
        sessionStorage.setItem('hmdj_stopError', true);
    } else {
        if (result.code) {
            var href = '../index.html';
            Common.fn.formatOutput(result, href);
            loading.hide();
            return false;
        }
    }
    var state = result.data.goods.state,
        sendState = result.data.goods.postage,
        endTime = result.data.goods.endTime,
        endYear = parseInt(endTime.substr(0, 4)),
        endMonth = parseInt(endTime.substr(5, 2)),
        endDay = parseInt(endTime.substr(8, 2)),
        endHour = parseInt(endTime.substr(11, 2)),
        endMinute = parseInt(endTime.substr(14, 2)),
        endSecond = parseInt(endTime.substr(17, 2)),
        targetEndTime = (new Date(endYear, endMonth - 1, endDay, endHour, endMinute, endSecond)).getTime(),
        portraits = result.data.collection;
    // 显示商品图片
    var imageObjs = [],
        urls = [],
        clientWidth = document.body.clientWidth * 0.3;
    for (var i = 0; i < result.data.images.length; i++) {
        var item = '<img class="goods-images-item" data-id="' + i + '" src="' + result.data.images[i].image + '">';
        $('.goods-detail-thumb-item').eq(i).append(item);
        urls.push(result.data.images[i].image);
        // 获取图片高度
        var thisWidth = parseInt($('.goods-detail-thumb-item img').eq(i).css('width')),
            thisHeight = parseInt($('.goods-detail-thumb-item img').eq(i).css('height')),
            present = (clientWidth / thisWidth) * 1.25;
        $('.goods-detail-thumb-item img').eq(i).css('height', thisHeight * present + 'px');
        $('.goods-detail-thumb-item img').eq(i).css('width', thisWidth * present + 'px');
    }
    for(var i = 0;i < urls.length;i++) {
        imageObjs['imageObj_' + i] = { urls: urls, current: urls[i] }
    }
    // 图片插件绑定
    $(document).on('click', '.goods-images-item', function() {
        var id = $(this).attr('data-id');
        previewImage.start(imageObjs['imageObj_' + id])
	});
    // 判断是否为分享进入，修改文字
    var isShare = Common.fn.getUrlParam('isShare');
    if(isShare) {
        $('#return-btn').text('进入红木大集');
    }
    // 关注按钮改变
    if (result.data.bussiness.attention == true) {
        // 已关注
        $('.attention-btn').text('已关注');
        $('.attention-btn').attr('data-state', 1);
    } else {
        $('.attention-btn').text('关注');
        $('.attention-btn').attr('data-state', 0);
    }
    // 判断该商品是否缴纳了参拍金
    if (result.data.bussiness.tenPrice.toString() == 'false') {
        $('.m-footer-bond-btn').css('display', 'block');
        $('.m-footer-buy-btn').css('display', 'none');
    }else {
        $('.m-footer-bond-btn').css('display', 'none');
        $('.m-footer-buy-btn').css('display', 'block');
    }
    // 判断商品是否为代理商品
    if (result.data.goods.proxy) {
        $('.m-footer-bond-btn').attr('href', 'payDeposit.html?bid=' + bid + '&proxy=' + result.data.goods.proxyId + '&gid=' + gid);
        $('.m-footer-buy-btn').attr('data-proxy', result.data.goods.proxyId);
    }else {
        $('.m-footer-bond-btn').attr('href', 'payDeposit.html?bid=' + bid + '&proxy=0&gid=' + gid);
    }
    // 设置其他信息
    $('.portrait-img').attr('src', result.data.bussiness.photo);
    $('.vendor-level').text('v' + result.data.bussiness.grade);
    $('h3').text(result.data.bussiness.nickname);
    $('.score').text(result.data.bussiness.credits);
    $('.bond').text(result.data.bussiness.bond);
    result.data.bussiness.auth == true ? $('.auth').text('已认证') : $('.auth').text('未认证');
    $('.goods-detail').text(result.data.goods.content);
    $('.topPrice').text(result.data.goods.topPrice);
    $('.order-count').text(result.data.goods.join_count);
    // $('.vendor-date').text(result.data.goods.createTime);
    $('.praiseNumber').text(result.data.goods.praiseNumber);
    $('.attention-btn').attr('data-id', result.data.bussiness.businessId);
    $('.m-footer-buy-btn').attr('data-id', result.data.goods.goodsId);
    $('.portrait-block').attr('href', 'shop_detail.html?id=' + result.data.bussiness.businessId);
    sendState ? $('.sendState').text('包邮') : $('.sendState').text('不包邮');
    // 判断商品是否被点赞
    if (result.data.goods.praise) {
        // 已点赞
        $('.like-icon').attr('src', '../img/icon/like_1.png');
    }
    // 显示点赞用户头像
    if(typeof(portraits) != 'undefined') {
        for (var i = 0; i < portraits.length; i++) {
            var item = '<a href="shop_detail.html?id=' + portraits[i].openid + '"><img class="lazy-img" data-original="' + portraits[i].photo + '" /></a>';
            $('.portraits').append(item);
        }
        // 图片懒加载
        lazyImg();
    }
    // 抢购倒计时
    var time = setInterval(function () {
        var currentTime = Date.now(),
            offsetTime = targetEndTime - currentTime;
        if (offsetTime < 0) {
            clearInterval(time);
            return false;
        }
        var offsetHour = Math.floor(offsetTime / (3600 * 1e3)),
            remainTime = offsetTime - (offsetHour * 3600 * 1e3),
            offsetMinute = Math.floor(remainTime / (60 * 1e3)),
            remainTime2 = remainTime - (offsetMinute * 60 * 1e3),
            offsetSecond = Math.floor(remainTime2 / 1e3);
        $('.offset-hour').text(offsetHour);
        $('.offset-minute').text(offsetMinute);
        $('.offset-second').text(offsetSecond);
        if (offsetHour == 0 && offsetMinute == 0 && offsetSecond == 0) {
            clearInterval(time);
        }
    }, 1000);
    // 判断当前商品是否可购买
    switch (state) {
        // 售出
        case 0:
            $('.m-footer-buy-btn').text('已售出');
            $('.m-footer-buy-btn').css('background', '#ccc');
            break;
            // 上架
        case 1:
            // 购买事件设置
            $('.m-footer-buy-btn').on('click', function () {
                var proxy = '',
                    goodsId = $(this).attr('data-id');
                $(this).attr('data-proxy') ? proxy = $(this).attr('data-proxy') : proxy = 0;
                weui.confirm('请填写你的预期价位<br>最低1元，最高不封顶<input type="number" id="toPrice" style="border: 0;font-size: 3rem;text-align: center;width: 100%;border-bottom: 1px solid #000;">', {
                    title: '竞标',
                    buttons: [{
                        label: '取消',
                        type: 'default',
                        onClick: function () {
                            console.log('no')
                        }
                    }, {
                        label: '确认竞标',
                        type: 'primary',
                        onClick: function () {
                            // 判断出价是否高于起降价
                            // 判断输入值是否合法
                            var regu = "^[0-9]+[\.][0-9]{0,3}$",
                                re = new RegExp(regu),
                                s = $.trim($('#toPrice').val());
                            if (s.indexOf('.') < 0) {
                                s += '.00';
                            }
                            if (re.test(s)) {
                                // 输入合法
                                var loading = weui.loading('loading', {
                                    className: 'custom-classname'
                                });
                                var result = Model.order.offerPrice({
                                    price: parseInt(s),
                                    proxyId: proxy,
                                    goodsId: goodsId
                                });
                                switch (parseInt(result.code)) {
                                    // 用户未缴纳10元押金
                                    case 10804:
                                        alert(result.message);
                                        location.href = 'payDeposit.html?proxy=' + proxy + '&gid=' + goodsId;
                                        break;
                                        // 用户未完善收货地址
                                    case 10710:
                                        alert(result.message);
                                        location.href = 'address.html';
                                        break;
                                    case 0:
                                        alert(result.data);
                                        location.reload();
                                        break;
                                    default:
                                        alert(result.message);
                                        location.reload();
                                        break;
                                }
                                loading.hide();
                            } else {
                                // 输入不合法
                                alert('输入金额不符合规范');
                                return false;
                            }
                        }
                    }]
                });
            });
            break;
            // 下架
        case 2:
            $('.m-footer-buy-btn').text('已下架');
            $('.m-footer-buy-btn').css('background', '#ccc');
            break;
    }
    var info = result.data.goods.content,
		img = result.data.images[0].image;
    Model.wechat.weShare(gid, info, img);
    loading.hide();
});

// 关注按钮
$(document).on('click', '.attention-btn', function () {
    var id = $(this).attr('data-id'),
        state = $(this).attr('data-state');
    if (state == 1) {
        // 已关注
        weui.confirm(
            "真的要取消关注吗？",
            function () {
                // 取消关注
                result = Model.business.attendBusiness({
                    businessId: id
                });
                if (result.code) {
                    alert(result.message);
                    location.reload();
                    return false;
                }
                location.reload();
            },
            function () {}
        );
    } else {
        // 关注店铺
        var loading = weui.loading('loading', {
            className: 'custom-classname'
        });
        result = Model.business.attendBusiness({
            businessId: id
        });
        if (result.code) {
            Common.fn.formatOutput(result);
            return false;
        }
        loading.hide();
        location.reload();
    }
});

// 点赞按钮
$(document).on('click', '.like-icon', function () {
    var gid = Common.fn.getUrlParam('gid'),
        result = Model.goods.collectGoods({
            goodId: gid
        });
    if (result.code) {
        Common.fn.formatOutput(result);
        return false;
    }
    location.reload();
});

// 分享
$(document).on('click', '.share-btn', function () {
    weui.alert('请点击右上角菜单 -> 发送给朋友或分享到朋友圈 进行分享');
});

/* // 点击头像跳转店铺
$(document).on('click', '.portrait-block', function () {
    var id = $(this).attr('data-id');
    location.href = 'shop_detail.html?id=' + id;
}); */

// 点击图片放大
/* $(document).on('click', '.goods-images-item', function () {
    var url = $(this).attr('src');
    var gallery = weui.gallery(url, {
        className: 'custom-classname',
        onDelete: function () {
            gallery.hide(function () {
                console.log('`gallery` has been hidden');
            });
        }
    });
}); */

// 图片懒加载
function lazyImg() {
    $(".lazy-img").lazyload({
        effect: "fadeIn"
    });
}